package com.example.dingdong.config;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 配置跨域问题的拦截器
 */
public class CorsInterceptor extends HandlerInterceptorAdapter {

   /**
    * 处理请求前的操作
    *
    * @param request  当前HTTP请求
    * @param response 当前HTTP响应
    * @param handler  处理器（从控制器中获取）
    * @return boolean 如果返回true，则继续处理请求；如果返回false，则请求被终止
    */
   @Override
   public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
      // 允许所有来源的请求
      response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
      // 允许的请求方法
      response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
      // 预检请求的缓存时间（秒）
      response.setHeader("Access-Control-Max-Age", "3600");
      // 允许的请求头
      response.setHeader("Access-Control-Allow-Headers", "x_requested_with,x-requested-with,Authorization,Content-Type,token");
      // 允许发送凭据
      response.setHeader("Access-Control-Allow-Credentials", "true");
      return true;
   }
}
